import React from 'react';
import Tree from '../../components/tree';

import {Row,Col,Select,Input,Button,Table,Card,message,Modal,Form,Cascader,Tooltip} from 'antd';
import {connect} from 'dva'
import { formatCascader } from '../../common/common';
import { Num_Str } from '../../common/system';
import { selectDeptTree, getAreaDetail, getUserByDeptId, userDel, userAdd, userUpdate, selectAllRole, addArea , updateDept, delDept} from '../../services/api';
const confirm = Modal.confirm;

@Form.create()
class Manage extends React.Component {

	state = {
		deptTree: [], //区域树结构
		dataSroce: [],
		selectedRowKeys: [], // 多选的id集合
		pageParam: {
			current: 1,
			pageSize: 20,
			total: 2
		},
		chooseData: {1: '123', 2: '456'},
		fid: 0,
		detailData: null,
		roleArr: [],
		// only:true,  //表示单删。false表示批量删

		code:'',  
		deptLoading:false,
	};
	columns = [
		{ title: '姓名', dataIndex: 'fUserName' },
		{ title: '登录名', dataIndex: 'fLoginName' },
		{ title: '操作',
		 width: 130,
			align: 'center',
			 render: (val, obj) =>
			  <Row style={{ width: '100%' }} type="flex" justify="space-around">
				<Col>
					<a onClick={()=>this.setState({visible: true, userId: obj.fId, name: obj.fUserName, username: obj.fLoginName })}>修改</a>
				</Col>
				<Col><a onClick={()=>this.deleteUser(obj.fId,true)}>删除</a></Col>
			  </Row> }
	];

	componentDidMount() {
		this.getDeptTreeData();
		this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
		this.getAllRole();
		// this.getAreaDetailAjax()
	}
   
	async getAllRole() {
		const response = await selectAllRole();
		if (response.code === 200) {
			this.setState({ roleArr: response.data })
		} else {
			response.msg && message.error(response.msg);
		}
	}

	//获取区域信息
	async getDeptTreeData() {
		const response = await selectDeptTree();
		if (response.code === 200) {
			this.setState({ deptTree: response.data })
		} else {
			response.msg && message.error(response.msg);
		}
	}

	//获取区域详细信息
	async getDeptDetail() {
		const response = await selectDeptTree();
		if (response.code === 200) {
			this.setState({ deptTree: response.data })
		} else {
			response.msg && message.error(response.msg);
		}
	}
	/**
	 * 获取左侧角色树当前选中的角色
	*/
	selectNode = (val) => {
		this.setState({
			fid: val[0],
			edit: false
		});
		if (!val[0]) {
			this.setState({
				selectedRowKeys:[],
				dataSroce: [],
				detailData: null
			});
			return;
		}
		this.getAreaDetailAjax(val[0]);
		this.getUserByDeptIdAjax(val[0]);
	}

	async getUserByDeptIdAjax(fid) {
		if (this.state.loadingUser) {
			return;
		}
		this.setState({loadingUser: true})
		const response = await getUserByDeptId(fid);
		this.setState({loadingUser: false})
		if (response.code === 200) {
			if (response.data) {
				this.setState({dataSroce: response.data})
			}
		} else {
			message.error(response.msg);
		}
	}

	async getAreaDetailAjax (fid) {
		if (this.state.loading) {
			return;
		}
		this.setState({loading: true})
		const response = await getAreaDetail(fid);
		this.setState({loading: false})
		if (response.code === 200) {
			if (response.data) {
				this.setState({
					detailData: response.data,
					code:response.data.fDeptCode
				})
			}
		} else {
			this.setState({loading: false})
			message.error(response.msg);
		}
	}
	/**
	 * 获取右侧权限树已选中权限（id）
	*/

	// 切换选中状态
	onSelectChange = (val) => {
		this.setState({ selectedRowKeys: val });
		
	}

	getId(arr1,arr2){
		let arr = [];
		for(let i=0;i<arr1.length;i++){
           for(let j=0;j<arr2.length;j++){
			   if(arr1[i] === j ){
                    arr.push(arr2[j].fId);
			   }
		   }  
		}
		return arr;
	}

	// 表格 表头
	tableTitle = () => {
		return (
			<Row type="flex" justify="space-between">
				<Col>用户列表</Col>
				<Col>
					<Button type="primary" size="small" style={{ marginRight: 20 }} onClick={()=>this.setState({visible: true,userId: ''})}>新增</Button>		
					<Button type="danger" size="small"  onClick={()=>this.deleteUser(false)}>删除</Button>
				</Col>
			</Row>
		)
	}

	// 删除用户列表数据
	deleteUser(fid,flag) {
		// 用户列表id集合
		const ids = fid ? [fid]: this.state.selectedRowKeys;
		if(ids.length <= 0){
			message.warning('请至少选择一条您要进行操作的数据');
			return;
		}
		const id = this.getId(this.state.selectedRowKeys,this.state.dataSroce);
		confirm({
			title: '提示',
			content: `您确认要删除${ids.length}个用户吗?`,
			okText: '确认',
			cancelText: '取消',
			onOk: ()=> {
				this.testDel(fid,flag,id);
			},
			onCancel:()=> {
				if (this.state.delLoading) {
				message.warning('处理中,请稍后');
				return new Promise((resolve, reject)=> {
					while (!this.state.delLoading) {
					resolve();
					}
				})
				}
			},
    });
	}

	
	async testDel(fid,flag,id) {
		// 一个loading的处理
		this.setState({ delLoading: true });
		this.setState({ delLoading: false });
		let data = flag === true ? await userDel({userIdList:[fid]}) : await userDel({userIdList:id})
		if (data.code === 200) {
			this.setState({
				selectedRowKeys:[]
			})
			 this.getUserByDeptIdAjax(this.state.fid);
			 this.getAreaDetailAjax(this.state.fid);
			 message.success('删除成功')
		} else {
			message.error(data.msg);
		}
	}

	// 详情
	detailTitle = () => {
		return (
			<Row type="flex" justify="space-between">
				<Col>
					区域详情
				</Col>
				<Col>
					<Button type="primary" size="small">修改</Button>	
					<Button type="danger" size="small">删除</Button>	
				</Col>
			</Row>
		);
	}
	// 区域详情切换至修改状态
	changeUpdate = () => {
		this.setState({
			edit: true,
			[`${this.state.detailData.fId}dept`]: this.state.detailData.fDeptPCodeList.split(','),
			[`${this.state.detailData.fId}admin`]: this.state.detailData.fAdminUser,
			[`${this.state.detailData.fId}role`]: this.state.detailData.roleId.split(','),
			[`${this.state.detailData.fId}name`]: this.state.detailData.fName,
			
		});
	}

	hideModal= () => {
		if (this.state.userLoading) {
			message.warning('正在处理中,请稍后')
			return;
		}
		this.setState({
			visible: false,
			name: '',
			username: '',
			password: '',
		});
		this.props.form.resetFields();
	}
	// 提交用户列表 信息修改或增加的方法
	handleSubmit = () => {
		this.props.form.validateFields((err, values) => {
			if (err.name || err.username || err.password) {
				return;
			}
			
			this.setState({userLoading: true});
			if (!this.state.userId) {
				userAdd({
					fLoginName: values.username.trim(),
					fPassword: values.password.trim(),
					fUserName: values.name.trim() ,
					listDept: this.state.userId?undefined: (this.state.detailData.fId).split(','),
					fId: this.state.userId ? this.state.userId: undefined
				})
				.then((data)=>{
					// 接口调用
					// 成功之后的处理 1. 关闭loading 2. 刷新当前页的数据, 如果是新增则跳转第一页 3. 关闭modal
					this.setState({userLoading: false});
					if (data.code === 200) {
						this.setState({
							visible: false,
							// 重置文本框中的内容
							name: '',
							username: '',
							password: ''
						});
						this.props.form.resetFields();
						this.getUserByDeptIdAjax(this.state.fid);
						message.success('新增成功')
					} else {
						message.error(data.msg);
					}
				})
			} else {
				userUpdate({
					fLoginName: values.username.trim(),
					fPassword: values.password.trim(),
					fUserName: values.name.trim() ,
					listDept: this.state.userId?undefined: (this.state.detailData.fDeptPCodeList+`,${this.state.detailData.fDeptCode}`).split(','),
					fId: this.state.userId ? this.state.userId: undefined
				})
				.then((data)=>{
					// 接口调用
					// 成功之后的处理 1. 关闭loading 2. 刷新当前页的数据, 如果是新增则跳转第一页 3. 关闭modal
					this.setState({userLoading: false});
					if(sessionStorage.getItem('fLoginName') === this.state.username){
						if (data.code === 200) {
							this.setState({
								visible: false,
								// 重置文本框中的内容
								name: '',
								username: '',
								password: ''
							});
							this.props.form.resetFields();
							this.getUserByDeptIdAjax(this.state.fid);
							sessionStorage.clear();
							this.props.history.push('/');
							message.error('用户信息已修改，请重新登录');
							
							// message.success('修改成功')
						} else {
							message.error(data.msg);
						}
					 } else {
						if (data.code === 200) {
							this.setState({
								visible: false,
								// 重置文本框中的内容
								name: '',
								username: '',
								password: ''
							});
							this.props.form.resetFields();
							this.getUserByDeptIdAjax(this.state.fid);
							message.success('修改成功')
						} else {
							message.error(data.msg);
						}
					 }
					
			
				})
			}
    });
	}
	// 删除区域详情
	deleteDetail = () => {
		confirm({
			title: '提示',
			content: `您确认要删除该区域详情吗?`,
			okText: '确认',
			cancelText: '取消',
			onOk: ()=> {
				// 一个loading的处理
				this.setState({ delLoading: true });
				return new Promise((resolve, reject)=> {
							// 删除接口的处理
							// 成功的处理
							delDept(this.state.detailData.fId)
							.then((data)=>{
								if (data.code === 200) {
									resolve(); // 成功的返回
									this.setState({
										detailData: null,
										delLoading: false 
									});
									this.getDeptTreeData();
									this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
									message.success('删除成功')
								} else {
									this.setState({ delLoading: false });
									message.error(data.msg);
									setTimeout(function(){
										resolve();
									},500)	
								}
							})
				}).catch(() => console.log('删除出错'));
			},
			onCancel:()=> {
				if (this.state.delLoading) {
				message.warning('处理中,请稍后');
				return new Promise((resolve, reject)=> {
					while (!this.state.delLoading) {
					resolve();
					}
				})
				}
			},
    });	
	}	
	// 新增区域的提交
	handleSubmitArea = () => {
		this.props.form.validateFields((err, values) => {
      if (err.name || err.role || err.father) {
				return;
			}
			// values 是提交的数据
			this.setState({areaLoading: true});
			addArea({
				fName: values.name.trim(),
				fDeptPCode: values.father?values.father[values.father.length-1]:undefined,
				roleId: 'caf9f02219bf43dd8bff7f0a25b08807'
			})
			.then((data)=>{
				this.setState({areaLoading: false});
				if (data.code === 200) {
					
					this.setState({
						addArea: false
					});
					this.props.form.resetFields();
					this.getDeptTreeData();
					this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
					message.success('新增成功')
				} else {
					this.setState({areaLoading: false});
					message.error(data.msg);
				}
			})
			
			// 接口调用
			// 成功之后的处理 1. 关闭loading 2. 刷新当前页的数据, 如果是新增则跳转第一页 3. 关闭modal
			
    });
	}
	checkTextArea = (rule, value, callback) => {
		if (value && value.trim().length>100 ) {
			callback('字数不能超过100');
			return;
		}
		callback();
	}

	//修改保存
	saveRole= async () => {
		this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
		const name = this.state[`${this.state.detailData.fId}name`];
		const admin = this.state[`${this.state.detailData.fId}admin`];
		const role = this.state[`${this.state.detailData.fId}role`]?this.state[`${this.state.detailData.fId}role`][this.state[`${this.state.detailData.fId}role`].length-1]:undefined;
		const dept = this.state[`${this.state.detailData.fId}dept`]?this.state[`${this.state.detailData.fId}dept`][this.state[`${this.state.detailData.fId}dept`].length-1]: undefined;
		if (!name || (name && name.trim().length === 0)) {
			message.warning('名称不能为空');
			return;
		}
		// if (!admin) {
		// 	message.warning('管理员不能为空');
		// 	return;
		// }
		if (!role) {
			message.warning('角色不能为空');
			return;
		}
		if (!dept) {
			message.warning('父级不能为空');
			return;
		}
		this.setState({deptLoading:true})
		const response = await updateDept({fName: name, roleId: role, fId: this.state.detailData.fId,fDeptPCode: dept, fAdminUser: admin,fDeptCode:this.state.code});
		if (response.code === 200) {
			this.setState({
				edit: false,
				deptLoading:false
			},()=>{
				this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
				this.getAreaDetailAjax(this.state.fid);
				this.getDeptTreeData();
				this.getAllRole()
			})	
			message.success('保存成功')	
		} else {
			message.error(response.msg);
			this.setState({deptLoading:false})
		}
	}

	// 关闭新增区域
	hideModalArea = () => {
		if (this.state.userLoading) {
			message.warning('正在处理中,请稍后')
			return;
		}
		this.setState({
			addArea: false,
			name: '',
			username: '',
			password: '',
		});
		this.props.form.resetFields();
	}
	render() {
		const rowSelection = {
			selectedRowKeys: this.state.selectedRowKeys,
			onChange: this.onSelectChange,
		};
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
		};

		return (
			<Row>
				<Col span={6}>
					<Card title={<Row type="flex" justify="space-between">
												<Col>
													区域列表
												</Col>
												<Col>
													<Button type="primary" size="small" onClick={()=>this.setState({addArea: true})}>新增</Button>
												</Col>
											</Row>}>
						<Tree data={this.state.deptTree} name="fName" id="fId" selectNode={this.selectNode} />
					</Card>
				</Col>
				<Col span={17}>
					{this.state.detailData ? 
					<Card style={{overflow:'scroll'}}
						title={<Row type="flex" justify="space-between">
										<Col>
											区域详情
										</Col>
										<Col>
											{
												this.state.fid === this.state.deptTree[0].fId ? "" : (this.state.edit) ?
												  <div>
												  <Button type="primary" size="small" style={{marginRight: 20}} onClick={this.saveRole} loading={this.state.deptLoading}>保存</Button><Button type="primary" size="small"  onClick={()=>this.setState({edit: false})}>取消</Button>
												  </div>:
													<div>
													<Button type="primary" size="small" style={{marginRight: 20}} onClick={this.changeUpdate}>修改</Button><Button type="danger" size="small" onClick={()=>this.deleteDetail()}>删除</Button>
												  </div>
											}
											
										</Col>
									</Row>}
			 			style={{ width: '100%' }}
					>
						<Row style={{marginBottom: 10}}>
							<Col span={8}>
								<Row>
									<Col span={4}>
										<span>名称：</span>
									</Col>
									<Col push={1} span={17}>
									{ 
										this.state.edit ?
									
										<Input value={this.state[`${this.state.detailData.fId}name`]} maxLength="10" onChange={(e)=>this.setState({[`${this.state.detailData.fId}name`]: e.target.value.trim()})} />
									: <span>{this.state.detailData.fName}</span> }
									</Col>
								</Row>
							</Col>
							<Col span={8}>
								<Row>
									<Col span={4}>
										<span>管理员：</span>
									</Col>
									<Col push={1} span={17}>
									 { this.state.edit ?
										<Select style={{width: '100%'}} value={this.state[`${this.state.detailData.fId}admin`]} onChange={(e)=>this.setState({[`${this.state.detailData.fId}admin`]: e})} >
											{this.state.dataSroce.map((data)=>{
												return <Select.Option value={data.fId} key={data}>{data.fUserName}</Select.Option>
											})}
										</Select>
										: <span>{this.state.detailData.fAdminUserName}</span> }
									</Col>
								</Row>
							</Col>
							
							{/* <Col span={6}>
								<Row>
									<Col span={4}>
										<span>角色：</span>
									</Col>
									<Col push={1} span={17}>
										{ this.state.edit ?
										<Cascader style={{width: '100%'}} value={this.state[`${this.state.detailData.fId}role`]} changeOnSelect onChange={(e)=>this.setState({[`${this.state.detailData.fId}role`]: e})} options={formatCascader(this.state.roleArr, 'fId', 'fRoleName', 'children')} placeholder="请选择..."/>
										: <span>{this.state.detailData.fRoleName}</span> }
									</Col>
								</Row>
							</Col> */}
							<Col span={8}>
								<Row>
									<Col span={4}>
										<span>父级：</span>
									</Col>
									<Col push={1} span={17}>
									{ this.state.edit ?
										<Cascader style={{width: '100%'}} value={this.state[`${this.state.detailData.fId}dept`]} changeOnSelect onChange={(e)=>{this.setState({[`${this.state.detailData.fId}dept`]: e})}} options={formatCascader(this.props.areaInfo, 'fId', 'fName', 'children')} placeholder="请选择..."/>
										: <Tooltip title={this.state.detailData.fDeptPNameList}>
										     <span>{this.state.detailData.fDeptPNameList.length >5 ? this.state.detailData.fDeptPNameList.slice(0,5)+'...' :this.state.detailData.fDeptPNameList }</span>
									      </Tooltip>
									 }
									</Col>
								</Row>
							</Col>
						</Row>
						<Table
							rowKey="fId"
							title={this.tableTitle}
							bordered
							size="small"
							columns={this.columns}
							dataSource={this.state.dataSroce}
							rowSelection={rowSelection}
							pagination={false}
						/>
					</Card> : null}
				</Col>
				<Modal
                    title={this.state.userId?'用户修改':'用户新增'}
					visible={this.state.visible}
					confirmLoading={this.state.userLoading}
                    onOk={this.handleSubmit}
          			onCancel={this.hideModal}
          			okText="确认"
					cancelText="取消"
					maskClosable={false}
        		>
					<Form >
						<Form.Item
							{...formItemLayout}
							label="姓名"
						>
							{getFieldDecorator('name', {
								initialValue: this.state.name?this.state.name: '',
								rules: [{
									required: true, message: '请输入姓名',
									whitespace: true, message: '请输入姓名'
								}],
							})(
								<Input  maxLength={'20'} placeholder="请输入"/>
							)}
						</Form.Item>
						<Form.Item 
							{...formItemLayout}
							label="用户名"
						>
							{getFieldDecorator('username', {
								initialValue: this.state.username?this.state.username: '',
								rules: [{
									required: true, message: '请输入用户名',
									whitespace: true, message: '请输入用户名'
								},{
									pattern: Num_Str, message: '用户名只能是字母和数字组合'
								}],
							})(
								<Input  maxLength={'15'} placeholder="请输入"/>
							)}
						</Form.Item>
						<Form.Item  
							{...formItemLayout}
							label="密码"
						>
							{getFieldDecorator('password', {
								initialValue: this.state.password ? this.state.password: '',
								rules: [{
									required: true, message: '请输入密码',
									whitespace: true, message: '请输入密码'
								}],
							})(
								<Input name="21" id="21" maxLength={'20'} type="password" placeholder="请输入"/>
							)}
						</Form.Item>
					</Form>
        </Modal>
				<Modal
          			title={'新增区域'}
          			visible={this.state.addArea}
          			onOk={this.handleSubmitArea}
					onCancel={this.hideModalArea}
					confirmLoading={this.state.areaLoading}
          			okText="确认"
					cancelText="取消"
					maskClosable={false}
        >
					<Form>
						<Form.Item
							{...formItemLayout}
							label="名称"
						>
							{getFieldDecorator('name', {
								rules: [{
									required: true, message: '请输入名称',
									whitespace: true, message: '请输入名称'
								}],
							})(
								<Input maxLength={'20'} placeholder="请输入"/>
							)}
						</Form.Item>
						{/* <Form.Item
							{...formItemLayout}
							label="角色"
						>
							{getFieldDecorator('role', {
								rules: [{
									required: true, message: '请选择角色',
								}],
							})(
								<Cascader style={{width: '100%'}} changeOnSelect options={formatCascader(this.state.roleArr, 'fId', 'fRoleName', 'children')} placeholder="请选择..."/>
							)}
						</Form.Item> */}
						<Form.Item
							{...formItemLayout}
							label="父级"
						>
							{getFieldDecorator('father', {
								rules: [{
									required: true, message: '请选择父级',
								}],
								
							})(
								<Cascader style={{width: '100%'}} changeOnSelect options={formatCascader(this.props.areaInfo, 'fDeptCode', 'fName', 'children')} placeholder="请选择..."/>
							)}
						</Form.Item>
					</Form>
               </Modal>
			</Row>
		);
	}

}

export default connect((state)=>({
	oldDetailModal: state.example.oldDetailModal,
	addModal: state.example.addModal,
	distributeModal: state.example.distributeModal,
	areaInfo: state.example.areaInfo,
    serviceType:state.example.serviceType,
    servicePersons:state.example.servicePersons,
}))(Manage)